package br.edu.ufabc.gtrnp.helppo.presentation.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;

import br.edu.ufabc.gtrnp.helppo.persistence.HibernateUtil;

public class HibernateSessionRequestFilter implements Filter {

	private SessionFactory sessionFactory;

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		try {
			sessionFactory.getCurrentSession().beginTransaction();
			chain.doFilter(request, response);

			sessionFactory.getCurrentSession().getTransaction().commit();

		} catch (StaleObjectStateException staleEx) {
			throw staleEx;
		} catch (Throwable ex) {
			ex.printStackTrace();
			try {
				if (sessionFactory.getCurrentSession().getTransaction().isActive()) {
					sessionFactory.getCurrentSession().getTransaction().rollback();
				}
			} catch (Throwable rbEx) {
				System.out.println("Could not rollback transaction after exception!");
			}
			throw new ServletException(ex);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	public void destroy() {
	}

}
